<template>
  <div>
    <!-- <h1>角色列表</h1> -->
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col> <el-button type="primary">添加角色</el-button></el-col>
      </el-row>
      <!-- row-key="id" -->
      <el-table :data="roleList" border>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <!-- 权限渲染 -->
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="onDleRight(scope.row.id, item1.id, scope.row)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="onDleRight(scope.row.id, item2.id, item1)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      @close="onDleRight(scope.row.id, item3.id, item2)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
          <!-- ------------------------------------------------------------------ -->
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- slot-scope="scope" -->
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRoleRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :visible.sync="isShow" width="50%" title="提示">
      <!-- <span>这是一个dialog</span> -->
      <!-- 树形控件 -->
      <el-tree
        :data="rightstree"
        ref="treeRef"
        :default-checked-keys="checkedRlightIds"
        default-expand-all
        :props="{ children: 'children', label: 'authName' }"
        node-key="id"
        show-checkbox
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [], //角色数据
      isShow: false, //权限分配对话框显示与否

      rightstree: [], //权限数据
      checkedRlightIds: [101], //已有权限

      rId: -1, //权限树角色id
    }
  },
  created() {
    // 获取角色
    this.getRoleList()
    // 获取权限树
    this.getRighsTree()
  },
  methods: {
    // 获取数据
    async getRoleList() {
      const { data: res } = await this.$axios.get('roles')
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$msg.error('获取角色列表失败')
      // //如果返回状态正常，将请求的数据保存在data中
      // this.roleList = res.data
      // console.log(res.data)
      this.roleList = res.data
    },
    // 删除权限
    onDleRight(roleId, id, father) {
      // console.log(id)
      this.$msgBox.confirm('您确定删除此权限吗', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: async (action) => {
          // 点击确认
          if (action == 'confirm') {
            // console.log(id)
            const { data: res } = await this.$axios({
              url: `roles/${roleId}/rights/${id}`,
              method: 'delete',
            })
            console.log(res)
            // 删除失败
            if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
            // 删除成功重新渲染，将父级的childern删除响应的属性
            const targeIndex = father.children.findIndex((e) => {
              // childern
              return e.id == id
            })
            targeIndex > -1 && father.children.splice(targeIndex, 1)
          } else {
            // 点击取消
            return this.$msg.info('取消删除成功')
          }
        },
      })
    },
    // 显示权限树
    showRoleRights(role) {
      this.rId = role.id

      this.isShow = true

      // 必须重新获取权限树
      this.getRighsTree()

      this.checkedRlightIds = []

      this.getRoleYes(role)
    },
    // 获取权限过程
    async getRighsTree() {
      const { data: res } = await this.$axios({
        url: 'rights/tree',
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

      this.rightstree = res.data
      // console.log(this.rightstree)
    },

    getRoleYes(father) {
      // console.log(11)
      // console.log(father)
      if (!father.children) return this.checkedRlightIds.push(father.id)

      father.children.forEach((element) => {
        this.getRoleYes(element)
      })
    },

    async allotRights() {
      //当用户在树形权限对话框中点击确定，将用户选择的
      //权限发送请求进行更新

      //获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      //将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')

      console.log(idStr)
      console.log(this.rId)

      //发送请求完成更新
      const { data: res } = await this.$axios.post(`roles/${this.rId}/rights`, {
        rids: idStr,
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)

      this.$msg.success(res.meta.msg)
      this.getRoleList()
      //关闭对话框
      this.isShow = false
    },
  },
}
</script>

<style scope  lang= less>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>